import { h, init } from 'snabbdom'
import style from 'snabbdom/modules/style'
import eventlisteners from 'snabbdom/modules/eventlisteners'

let data = [
  {
    id: '1',
    title: 'C第一部电影',
    des: 'A这是好的'
  },
  {
    id: '2',
    title: 'B第二部电影',
    des: 'B这是坏的'
  },
  {
    id: '3',
    title: 'A第三部电影',
    des: 'C这是坏的'
  }
]

let patch = init([
  style,
  eventlisteners
])

function renderList(list) {
  let listNode = []
  list.forEach((item, index) => {
    listNode.push(
      h('li',[
        h('span', item.id),
        h('span', item.title),
        h('span', item.des),
        h('button', {
          on: {
            click: [removeHandler, index]
          }
        }, 'X'),
      ])
    )
  })
  
  return h('ul', {}, listNode)
}

function renderApp() {
  return h('div',[
    h('h1', 'Top 10 movies'),
    h('span', 'Sort by'),
    h('span.rank', {
      on: {
        click: [sortHandler, 'id']
      }
    }, 'Rank'),
    h('span.title', {
      on: {
        click: [sortHandler, 'title']
      }
    }, 'Title'),
    h('span.description', {
      on: {
        click: [sortHandler, 'des']
      }
    }, 'Description'),
    h('span.add', {
      on: {
        click: addHandler
      }
    }, 'Add'),
    renderList(data)
  ])
}


let vnode = renderApp()
let app = document.querySelector('#app')
let oldVnode = patch(app, vnode)
let sortFlag = false
function compare(propertyName) {
  return function(object1, object2) {
    var value1 = object1[propertyName]
    var value2 = object2[propertyName]
    if (value2 < value1) {
      return -1
    } else if (value2 > value1) {
      return  1
    } else {
      return 0
    }
  }
}
// 删除 li
function removeHandler(index) {
  data.splice(index, 1)
  oldVnode = patch(oldVnode, renderApp())
}
// 排序
function sortHandler(type) {
  data = data.sort(compare(type))
  oldVnode = patch(oldVnode, renderApp())
}
// 添加
function addHandler() {
  data.push({
    id: data.length + 1,
    title: '这是一部新的电影',
    des: '很好看'
  })
  oldVnode = patch(oldVnode, renderApp())
}